package com.wdb007.venus.wss.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.biz.manager.ConfigInfoManager;
import com.wdb007.venus.svc.facade.BookShelfService;
import com.wdb007.venus.wss.channelgroup.BookCaseChannelGroups;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;

@Service("wsPoliciesIssuedService")
@Sharable
@Scope("prototype")
public class WsPoliciesIssuedService implements WebSocketServerService{

	private static Logger logger = LoggerFactory.getLogger(WsPoliciesIssuedService.class);
	
	@Autowired
	private BookShelfService bookShelfService;
	@Autowired
	private ConfigInfoManager configInfoManager;
	
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		JSONObject jsonObj = JSON.parseObject(request);
		logger.info("WsPoliciesIssuedService receive Message: {}", request);
		String bookCaseId = jsonObj.getString("bookCaseId");
		String info = jsonObj.getString("info");
		//如果为null，则说明首次下发，或者直接从数据库中读取配置
		if(ObjectUtils.isEmpty(info)) {
			info = bookShelfService.getPolicyInfo(bookCaseId);
			jsonObj.put("info", (JSONObject) JSON.parse(info));
			jsonObj.put("versions", configInfoManager.getValue("versions"));
			jsonObj.put("http_url", configInfoManager.getValue("http_url"));
			jsonObj.put("web_url", configInfoManager.getValue("web_url"));
			jsonObj.put("text", configInfoManager.getValue("text"));
			
		}
		jsonObj.remove("bookCaseId");
		logger.info("debug {} : 给机柜[{}],下发策略[{}]",jsonObj.getString("action"), bookCaseId, jsonObj.toJSONString());
		BookCaseChannelGroups.broadcast(bookCaseId, jsonObj.toJSONString());
		return null;
	}

}
